<template>
  <div>
    <el-form
      ref="dataForm"
      slot="content"
      :rules="rules"
      :model="temp"
      label-position="right"
      :label-width="'82px'"
      :disabled="dialogStatus === 'detail'"
    >
      <div class="title">基本信息</div>
      <el-form-item
        label="账号"
        prop="account"
      >
        <el-input
          v-model.trim="temp.account"
          :disabled="dialogStatus === 'update'"
          maxlength="20"
          show-word-limit
          class="limit"
        />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-radio v-model="temp.sex" label="M">男</el-radio>
        <el-radio v-model="temp.sex" label="F">女</el-radio>
      </el-form-item>
      <el-form-item label="姓名" prop="realName">
        <el-input
          v-model.trim="temp.realName"
          maxlength="20"
          show-word-limit
          class="limit"
        />
      </el-form-item>
      <el-form-item label="昵称" prop="nickName">
        <el-input
          v-model.trim="temp.nickName"
          maxlength="20"
          show-word-limit
          class="limit"
        />
      </el-form-item>
      <el-form-item label="生日" prop="birthday">
        <el-date-picker
          v-model="temp.birthday"
          style="width: 100%"
          type="date"
        />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model.trim="temp.email"
          maxlength="50"
          show-word-limit
          class="limit"
        />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input
          v-model.trim="temp.phone"
          maxlength="11"
          show-word-limit
          class="limit"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="idCard" :rules="auth?rules.idCard[0]:rules.idCard[1]">
        <el-input
          v-model.trim="temp.idCard"
          maxlength="18"
          show-word-limit
          class="limit"
        />
      </el-form-item>
      <div class="title">岗位信息</div>
      <el-form-item label="组织" prop="orgId">
        <el-popover
          v-model="editUservisible"
          placement="top-start"
          trigger="click"
          :disabled="dialogStatus === 'detail'"
        >
          <el-tree
            class="tree"
            width="100%"
            :data="treePopover"
            :load="loadPopover"
            lazy
            :props="defaultProps"
            :default-expand-all="false"
            :expand-on-click-node="false"
            @node-click="selectOrg"
          />
          <el-input
            slot="reference"
            v-model="orgName"
            :readonly="false"
            @focus="orgFocus"
            @input="orgInputchange"
          />
        </el-popover>
      </el-form-item>
      <el-form-item label="岗位" prop="positionId">
        <el-select
          v-model="temp.positionId"
          style="width: 100%"
          class="filter-item"
        >
          <el-option
            v-for="item in positionList"
            :key="item.positionId"
            :label="item.name"
            :value="item.positionId"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import hrOrganizationApi from '@/framework/api/userCenter/hrOrganization'
import router from '@/router'
import hrPositionApi from '@/framework/api/userCenter/hrPosition'
import {
  checkEmail,
  checkUserName,
  checkAccountName,
  checkIdCard,
  checkPhone
} from '@/framework/utils/validate'
import { checkPhoneOrEmailOnly } from '@/framework/api/userCenter/sysUser'
import { encryption } from 'DQBasic-vue-component'
import idNumberVerificationApi from '@/framework/api/userCenter/idNumberVerification'

export default {
  name: 'DtUserForm',
  // props: {
  //   auth: {
  //     type: Boolean,
  //     default: false
  //   }
  // },
  data() {
    // 账号校验
    const validateUserName = async (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入账号'))
      } else if (!checkUserName(value)) {
        callback(new Error('账号长度1-20字母、数字组成（不区分大小写）'))
      } else if (!(await this.checkOnly(rule, value))) {
        callback(new Error('账号已存在'))
      } else {
        callback()
      }
    }
    // 姓名校验
    const validateAccountName = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入姓名'))
      } else if (!checkAccountName(value)) {
        callback(new Error('请输入汉字、字母、数字'))
      } else callback()
    }
    // 邮箱校验
    const validateEmail = async (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入邮箱'))
      } else if (!checkEmail(value)) {
        callback(new Error('邮箱格式错误'))
      } else if (!(await this.checkOnly(rule, value))) {
        callback(new Error('邮箱已存在'))
      } else callback()
    }
    // 手机号校验
    const validatePhone = async (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话'))
      } else if (!checkPhone(value)) {
        callback(new Error('电话格式错误'))
      } else if (!(await this.checkOnly(rule, value))) {
        callback(new Error('电话已存在'))
      } else callback()
    }
    // 身份证号校验
    const validateIdCard = (rule, value, callback) => {
      if (value && !checkIdCard(value)) {
        callback(new Error('身份证号格式错误'))
      } else callback()
    }
    return {
      rules: {
        sex: [
          {
            required: true,
            message: '请选择性别',
            trigger: 'blur'
          }
        ],
        account: [
          {
            required: true,
            trigger: 'blur',
            validator: validateUserName
          }
        ],
        email: [
          {
            required: true,
            trigger: 'blur',
            validator: validateEmail
          }
        ],
        phone: [
          {
            required: true,
            trigger: 'blur',
            validator: validatePhone
          }
        ],
        realName: [
          {
            required: true,
            trigger: 'blur',
            validator: validateAccountName
          }
        ],
        idCard: [
          {
            required: true,
            trigger: 'change',
            validator: validateIdCard
          },
          {
            required: false,
            trigger: 'change',
            validator: validateIdCard
          }

        ],
        orgId: [
          {
            required: true,
            message: '请选择组织',
            trigger: 'change'
          }
        ]
      },
      temp: {
        account: '',
        orgId: '',
        sex: 'M',
        email: '',
        phone: '',
        realName: '',
        idCard: ''
      },
      dialogStatus: '',
      editUservisible: false,
      treePopover: [],
      positionList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      orgName: '',
      currentOrg: {},
      selectOrgId: '',
      selectOrgName: '',
      auth: false
    }
  },
  mounted() {
    this.getAuthidcard()
  },
  methods: {
    getAuthidcard() {
      idNumberVerificationApi.getAuthidcard().then((res) => {
        this.auth = res.data
      })
    },
    async checkOnly(rule, value) {
      const form = {}
      form[rule.field] = value
      if (this.dialogStatus == 'update') {
        form.userId = this.temp.userId
      }
      const temp = encryption({
        data: form
      })
      const { message } = await checkPhoneOrEmailOnly(temp)
      if (message == '') {
        return true
      } else {
        return false
      }
    },
    openForm(selectedOrg, dialogStatus) {
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.getPositionList()
      if (router.history.current.name == 'UserManage' || router.history.current.name == 'UserAuthorization') {
        this.dialogStatus = dialogStatus
        if (this.dialogStatus == 'create') {
          this.temp.orgId = selectedOrg.id
          this.temp.name = selectedOrg.name
          this.orgName = selectedOrg.name
          this.currentOrg = selectedOrg
        } else {
          this.temp.orgId = selectedOrg.orgId
          this.orgName = selectedOrg.orgName
          this.temp = selectedOrg
        }
      } else {
        this.dialogStatus = dialogStatus
        this.reset()
      }
    },
    reset() {
      this.temp = {
        account: '',
        orgId: '',
        sex: 'M',
        email: '',
        phone: '',
        realName: '',
        idCard: ''
      }
      this.orgName = this.selectOrgName
      this.temp.orgId = this.selectOrgId
      this.resetForm('dataForm')
    },
    loadPopover(tree, resolve) {
      let orgid = ''
      if (!tree.data || tree.data.length == 0) {
        orgid = 0
      } else {
        orgid = tree.data.id
      }
      hrOrganizationApi.getOrgListTreeNode({ orgId: orgid }).then((res) => {
        const { data } = res
        if (router.history.current.name != 'UserManage' && orgid == 0) {
          this.temp.orgId = data[0].id
          this.orgName = data[0].name
          this.selectOrgId = data[0].id
          this.selectOrgName = data[0].name
        }
        resolve(data)
      })
    },
    // 选择机构
    selectOrg(data) {
      this.editUservisible = false
      this.temp.orgId = data.id
      this.orgName = data.name
      this.currentOrg = data
    },
    orgFocus() {
      hrOrganizationApi
        .getOrgListTreeNode({ orgId: 0, orgName: this.orgName })
        .then((res) => {
          const data = res.data.map((item, index) => {
            item.orgId = item.id
            item.orgName = item.name
            return item
          })
          this.treePopover = data
        })
    },
    orgInputchange() {
      hrOrganizationApi
        .getOrgListTreeNode({ orgId: 0, orgName: this.orgName })
        .then((res) => {
          const data = res.data.map((item, index) => {
            item.orgId = item.id
            item.orgName = item.name
            return item
          })
          this.treePopover = data
        })
      if (this.orgName == '') {
        this.orgName = ''
        this.temp.orgId = ''
      }
    },
    // 获取职位列表
    getPositionList() {
      hrPositionApi.fetchList().then((res) => {
        this.positionList = res.data
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.title{
  font-size: 16px;
  font-family: HarmonyOS Sans SC-Medium, HarmonyOS Sans SC;
  font-weight: 500;
  color: #131314;
  line-height: 24px;
  padding-bottom: 8px;
  border-bottom: 1px solid #EBEEF5;
  margin-bottom: 24px;
}
</style>
